import request from 'axios'
import { action, makeAutoObservable, observable, runInAction } from 'mobx'
import persist from './persist'
import AsyncStorage from '@react-native-async-storage/async-storage'

const Api = 'http://192.168.31.136:1128'

export default class BookApi {
  fetch = async (uri, options = { cached: true }) => {
    if (options.cached) {
      const data = await AsyncStorage.getItem(uri)
      if (data) {
        console.log(`BookApi From cache ${uri}`)
        return JSON.parse(data)
      }
    }
    const resp = await request.get(uri)
    if (resp.data.code != 0) {
      const error = new Error(`Error code: ${resp.data.code}`)
      error.code = resp.data.code
      throw error
    }
    if (options.cached) {
      await AsyncStorage.setItem(uri, JSON.stringify(resp.data.data))
    }
    console.log(`BookApi From server ${uri}`)
    return resp.data.data
  }

  fetchBooks = async () => {
    return await this.fetch(Api)
  }

  fetchBook = async id => {
    return await this.fetch(`${Api}/book/${id}`)
  }

  fetchBooksByAuthor = async (id, detail = 1, start = 0, count = 4) => {
    return await this.fetch(`${Api}/author/${id}?detail=${detail}&start=${start}&count=${count}`, { cached: false })
  }

  fetchBooksByCategory = async (id, detail = 1, start = 0, count = 4) => {
    return await this.fetch(`${Api}/category/${id}?detail=${detail}&start=${start}&count=${count}`, { cached: false })
  }

  fetchAricle = async id => {
    return await this.fetch(`${Api}/article/${id}`)
  }

  fetchChapters = async id => {
    return await this.fetch(`${Api}/book/chapters/${id}`)
  }

  fetchRecommentBooks = async (count = 6) => {
    return await this.fetch(`${Api}/recomment?count=${count}`, { cached: false })
  }

  fetchHotestBooks = async (count = 6) => {
    return await this.fetch(`${Api}/hotest?count=${count}`, { cached: false })
  }

  fetchNewlyBooks = async (count = 6) => {
    return await this.fetch(`${Api}/newly?count=${count}&detail=1`, { cached: false })
  }

  fetchDailyArticles = async (count = 3) => {
    return await this.fetch(`${Api}/daily/article?count=${count}`, { cached: false })
  }

  fetchSearchPlaceholder = async () => {
    return await this.fetch(`${Api}/search/placeholder`, { cached: false })
  }

  fetchSearchResult = async query => {
    return await this.fetch(`${Api}/search?q=${query}`, { cached: false })
  }

  fetchCategoiesList = async () => {
    return await this.fetch(`${Api}/category/list`)
  }

  fetchCategoryHotlyBooks = async (_id, count = 12) => {
    return await this.fetch(`${Api}/category/hotly/${_id}?count=${count}`, { cached: false })
  }

  fetchRank = async (count = 12, detail = 1) => {
    return await this.fetch(`${Api}/rank?count=${count}&detail=${detail}`, { cached: false })
  }

  getCoverUrl(filename) {
    return `${Api}/static/${filename}`
  }
}
